import './style.css'
import typescriptLogo from './typescript.svg'
import viteLogo from '/vite.svg'
import { setupCounter } from './counter.ts'
import { initWasm } from './wasm'
import { showMessage } from './myLib'

document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <div>
    <a href="https://vite.dev" target="_blank">
      <img src="${viteLogo}" class="logo" alt="Vite logo" />
    </a>
    <a href="https://www.typescriptlang.org/" target="_blank">
      <img src="${typescriptLogo}" class="logo vanilla" alt="TypeScript logo" />
    </a>
    <h1>Vite + TypeScript + WebAssembly</h1>
    <div class="card">
      <button id="counter" type="button"></button>
    </div>
    <div class="card">
      <h2>WebAssembly 演示</h2>
      <div>
        <input type="number" id="num1" value="5" min="0" />
        +
        <input type="number" id="num2" value="7" min="0" />
        =
        <span id="result">?</span>
      </div>
      <button id="calculate">计算</button>
    </div>
    <p class="read-the-docs">
      Click on the Vite and TypeScript logos to learn more
    </p>
  </div>
`

setupCounter(document.querySelector<HTMLButtonElement>('#counter')!)

// 初始化WebAssembly并设置计算按钮的事件处理程序
initWasm().then(({ add, test_add, decrypt_code }) => {
  const calculateButton = document.querySelector<HTMLButtonElement>('#calculate');
  const num1Input = document.querySelector<HTMLInputElement>('#num1');
  const num2Input = document.querySelector<HTMLInputElement>('#num2');
  const resultSpan = document.querySelector<HTMLSpanElement>('#result');

  if (calculateButton && num1Input && num2Input && resultSpan) {
    calculateButton.addEventListener('click', () => {
      const a = Number(num1Input.value || 0);
      const b = Number(num2Input.value || 0);
      const result = test_add(a, b);
      resultSpan.textContent = result?.toString() || '';
    });
    const result = decrypt_code("J0lyulXgNdvqn7yvGQTKdntGjuFcFjoLQV1Hpvi6R5tEMNHRQ+GqTmfZ9lbypky/fdXaPK9u/n8b0XRkBplI/CjQXB0lI43RBdmqJmEgLu/CHlqaf+H50FBwghtigMyYhXo5fUFwE8KKyh5Zqjjb63vrpsBqabQ6bE6qFEWSnm0=");
    console.log(result);    
  }
}).catch(err => {
  console.error('WebAssembly初始化失败:', err);
});
